/*
 * Copyright (c) 2010 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.fdaoud.rayures.spring;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;
import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_SINGLETON;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.controller.multipart.MultipartWrapper;
import net.sourceforge.stripes.format.Formatter;
import net.sourceforge.stripes.tag.TagErrorRenderer;
import net.sourceforge.stripes.validation.TypeConverter;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ScopeMetadata;
import org.springframework.context.annotation.ScopeMetadataResolver;

/**
 * Spring scope resolver that associates Stripes artifacts with the prototype scope.
 * 
 * @author Frederic Daoud
 */
public class RayuresScopeResolver implements ScopeMetadataResolver {
  private static final List<Class<?>> PROTOTYPE_TYPES = Arrays.asList(
    ActionBean.class,
    ActionBeanContext.class,
    Collection.class,
    Formatter.class,
    MultipartWrapper.class,
    TagErrorRenderer.class,
    TypeConverter.class
  );

  public ScopeMetadata resolveScopeMetadata(BeanDefinition beanDef) {
    ScopeMetadata scopeMetadata = new ScopeMetadata();
    String typeName = beanDef.getBeanClassName();

    try {
      Class<?> type = Class.forName(typeName);

      boolean foundPrototype = false;
      for (Class<?> prototypeType : PROTOTYPE_TYPES) {
        if (prototypeType.isAssignableFrom(type)) {
          scopeMetadata.setScopeName(SCOPE_PROTOTYPE);
          foundPrototype = true;
          break;
        }
      }
      if (!foundPrototype) {
        scopeMetadata.setScopeName(SCOPE_SINGLETON);
      }
      return scopeMetadata;
    }
    catch (Exception exc) {
      throw new RuntimeException("Unable to resolve type: " + typeName, exc);
    }
  }
}
